<template>
  <p-drawer
    placement="right"
    :closable="false"
    width="calc(100vw - 200px)"
    :visible="visible"
    :mask-closable="false"
    :destroy-on-close="true"
    @close="onClose"
  >
    <TaskTitle :title-name="titleName" />
    <div class="g-drawer-list-container">
      <TitleSecondary title="基本信息" />
      <FormBasicInfo
        ref="form"
        :form="form"
        :page-type="pageType"
        :data-source="saleList"
        @clear-list="clearList"
      />
      <TitleSecondary title="销售责任人" />
      <TableSale
        ref="table"
        :data-source="saleList"
        :page-type="pageType"
        :parent-id="form.salesOrganization"
        :plan-id="planId"
      />
      <BottomLine />
    </div>
    <ButtonGroup
      class="g-drawer-footer"
      :options="filterButtons"
      @click="handleButtonClick"
    />
  </p-drawer>
</template>

<script>
import monent from 'moment';
import FormBasicInfo from './FormBasicInfo.vue';
import TableSale from '@/components/task/TableSale.vue';
import { postForecast, postForecastData } from '@/api/forecast';

import DrawerMixin from './mixin';

export default {
  components: {
    FormBasicInfo,
    TableSale,
  },
  mixins: [DrawerMixin],
  data() {
    return {
      form: {
        salesOrganization: '',
        serialNumber: '',
        name: '',
        startTime: '',
        deadline: null,
        responsibleId: {
          key: '',
          label: '',
        },
        responsibleName: '',
        operatingOrganization: '',
      },
      planIdNew: undefined,
      saleList: [],
    };
  },

  computed: {
    footerButtons() {
      return [
        {
          key: 'submit',
          type: 'primary',
          label: '提交',
          auth: true,
        },
        {
          key: 'save',
          label: '保存',
          auth: true,
        },
        {
          key: 'close',
          label: '返回',
        },
      ];
    },
  },
  watch: {
    visible: {
      handler(val) {
        if (!val) return;
        const plan = this.detail || {};
        this.form = {
          salesOrganization: plan.salesOrganization || '',
          serialNumber: plan.serialNumber || undefined,
          name: plan.name || '',
          startTime: plan.startTime && monent(plan.startTime),
          endTime: plan.endTime && monent(plan.endTime),
          deadline: plan.deadline || null,
          responsibleId: {
            key: plan.responsibleId,
            label: plan.responsibleName || '',
          },
          operatingOrganization: plan.operatingOrganization,
        };
        const planSales = this.detail?.mforecastSalesList || [];
        this.saleList = planSales.map((item) => {
          return {
            ...item,
            responsibleId: {
              key: item.responsibleId,
              label: item.responsibleName,
            },
            salesGroup: {
              key: item.salesGroup,
              label: item.salesGroupName,
            },
            kapmGroup: {
              key: item.kapmGroup,
              label: item.kapmGroupName,
            },
          };
        });
      },
      immediate: true,
    },
  },

  methods: {
    clearList() {
      this.saleList = [];
    },
    onClose() {
      this.$emit('update:visible', false);
      this.$emit('fresh');
    },
    async checkData() {
      if (!this.saleList.length) {
        this.$message.error('请先填写表格内容！');
        return false;
      }
      const index = this.saleList.findIndex((item) => {
        return (
          !item.salesGroup?.key ||
          !item.responsibleId?.key ||
          !item.kapmGroup?.key
        );
      });
      if (index > -1) {
        this.$message.error(
          `销售责任人第 ${index + 1} 条数据未填写完整，请补充！`
        );
        return false;
      }
      return true;
    },

    // 获取流程id
    async submitData(operating) {
      const valid = await this.$refs.form.validate();
      if (!valid) return new Promise(() => {});
      if (operating === 2) {
        const isValid = await this.checkData();
        if (!isValid) return new Promise(() => {});
      }

      const mforecastSalesList = this.saleList.map((item) => {
        return {
          ...item,
          responsibleId: item.responsibleId?.key,
          responsibleName: item.responsibleId?.label,
          salesGroup: item.salesGroup?.key,
          salesGroupName: item.salesGroup?.label,
          kapmGroup: item.kapmGroup?.key,
          kapmGroupName: item.kapmGroup?.label,
          id: undefined,
        };
      });

      const res = await postForecastData({
        ...this.form,
        startTime: monent(this.form.startTime).format('YYYY-MM-01 00:00:00'),
        endTime: monent(this.form.endTime).format('YYYY-MM-01 00:00:00'),
        type: this.pageType,
        mforecastSalesList,
        responsibleId: this.form.responsibleId.key,
        responsibleName: this.form.responsibleId.label,
      });
      const bizId = res?.data?.data;
      return await postForecast({
        bizId,
        bizModule: this.pageType,
        currStatus: operating,
      });
    },

    async submitCallback() {
      await this.submitData(2);
      this.$message.success('提交成功！');
      this.closeCallback();
    },
    async saveCallback() {
      await this.submitData(1);
      this.$message.success('保存成功！');
      this.closeCallback();
    },
    closeCallback() {
      this.onClose();
    },
    handleButtonClick(key) {
      const fn = `${key}Callback`;
      this[fn] && this[fn]();
    },
  },
};
</script>


